﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Data.Services.Client;
using Social_Photos.Social_Photos_Services;
using System.IO;
using System.Text;
namespace Social_Photos
{
    public partial class UploadPhoto : PhoneApplicationPage
    {
        PhotoChooserTask photoChooser;
        private Photo currentPhoto;
        private byte[] _imageBytes;
        private string filename;
        private bool chooserCancelled = false;

        public UploadPhoto()
        {
            InitializeComponent();
            // Initialize the PhotoChooserTask and assign the Completed handler.
            photoChooser = new PhotoChooserTask();
            photoChooser.Completed +=
                new EventHandler<PhotoResult>(photoChooserTask_Completed);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            if (chooserCancelled == false)
            {
                photoChooser.Show();
            }
            else {
                return;
            }
        }
        private void OnSelectPhoto(object sender, EventArgs e)
        {
            try
            {
                // Display the PhotoChooser.
                photoChooser.Show();
            }
            catch (System.InvalidOperationException ex)
            {
                MessageBox.Show("The image could not be selected. \n" + ex.Message);
            }
        }
        private void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            // Get back the last PhotoInfo in the collection, which we just added.
        //    currentPhoto = App.ViewModel.Photos[App.ViewModel.Photos.Count - 1];

            if (e.TaskResult == TaskResult.OK)
            {
                // Set the file properties for the returned image.                
                string[] splitFileName = e.OriginalFileName.Split(new Char[] { '\\' });
                DateTime currentTime = DateTime.Now;
                string day = currentTime.Day.ToString();
                string month = currentTime.Month.ToString();
                string year = currentTime.Year.ToString();
                string hour = currentTime.Hour.ToString();
                string minute = currentTime.Minute.ToString();
                string second = currentTime.Second.ToString();

                filename = day + month + year + hour + minute + second;

                _imageBytes = new byte[(int)e.ChosenPhoto.Length];
                e.ChosenPhoto.Read(_imageBytes, 0, _imageBytes.Length);
                e.ChosenPhoto.Seek(0, System.IO.SeekOrigin.Begin);

                BitmapImage imageFromStream = new System.Windows.Media.Imaging.BitmapImage();
                imageFromStream.SetSource(e.ChosenPhoto);

                chooserCancelled = true;
                this.PhotoImage.Source = imageFromStream;

                // Reset the stream before we pass it to the service. 
                e.ChosenPhoto.Position = 0;
            }
            else
            {
                // Assume that the select photo operation was cancelled,
                // remove the added PhotoInfo and navigate back to the main page.
               // App.ViewModel.Photos.Remove(currentPhoto);
                chooserCancelled = true;
            }
        }
        /*---------------------------------------Upload-------------------------------------------*/
        public void upload()
        {
            string upload_url = UrlConfig.UPLOAD_PHOTO;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(upload_url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
            goBack();
        }

        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            try
            {

                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                string encoding = "iso-8859-1";
                Stream postStream = request.EndGetRequestStream(asynchronousResult);
                string boundary = Guid.NewGuid().ToString();
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

                string header = string.Format("--{0}", boundary);
                string footer = string.Format("--{0}--", boundary);

                StringBuilder contents = new StringBuilder();
                contents.AppendLine(header);

                string fileHeader = String.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"; ", "media", filename + ".jpg");
                string fileData = Encoding.GetEncoding(encoding).GetString(_imageBytes, 0, _imageBytes.Length);

                contents.AppendLine(fileHeader);
                contents.AppendLine(String.Format("Content-Type: {0};", "image/jpeg"));
                contents.AppendLine();
                contents.AppendLine(fileData);

                contents.AppendLine(footer);

                // Convert the string into a byte array. 
                byte[] byteArray = Encoding.GetEncoding(encoding).GetBytes(contents.ToString());

                // Write to the request stream. 
                postStream.Write(byteArray, 0, contents.ToString().Length);
                postStream.Close();

                // Start the asynchronous operation to get the response 
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
            }
            catch (Exception ex)
            {

            }
        }
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {

                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                // End the operation 
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                string responseString = streamRead.ReadToEnd();

                // Close the stream object 
                streamResponse.Close();
                streamRead.Close();
               
                // Release the HttpWebResponse 
                response.Close();

                
                
            }
            catch (Exception ex)
            {

            }
           
        }

        public void goBack() {
            this.requestProgress.Visibility = Visibility.Collapsed;
            this.requestProgress.IsIndeterminate = false;
            NavigationService.GoBack();     
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            this.requestProgress.Visibility = Visibility.Visible;
            this.requestProgress.IsIndeterminate = true;
            upload();
            
        }

    }
}